<?php

namespace App\Http\Controllers\home;

use App\Models\OauthUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\URL;
use Laravel\Socialite\Facades\Socialite;

class ThirdLoginController extends Controller
{
    //
    public function github(){
        //记录登录前的地址
        session(array("previous_url"=>URL::previous()));
//        dd(URL::previous());
        return Socialite::driver('github')->redirect();
    }

    public function githubCallBack(Request $request,OauthUser $oauthUseruser){
        $githubuser = Socialite::driver('github')->user();

//        dd($githubuser);
        //获取用户数据
        $user=[
            "openid"=>$githubuser->id,
            "type"=>3,
            "name"=>$githubuser->nickname,
            "avatar"=>$githubuser->avatar,
            "last_login_ip"=>$request->getClientIp(),
            "login_times"=>1,
            "email"=>$githubuser->email,
            "is_admin"=>"0",
        ];
        //判断是否第一次登陆，非第一次登陆则修改
        $userinfo=$oauthUseruser->select("id","login_times")->where("openid",$user['openid'])->where("type",$user['type'])->first();
        if($userinfo){
            $user['id']=$userinfo->id;
            $user['login_times']=$userinfo->login_times+1;
        }
            $result=$oauthUseruser->storeData($user);
        //操作成功，将数据存进session
        if($result){
            $sessiondata=[
                "user"=>[
                    "id"=>$userinfo?$userinfo->id:$result->id,
                    "type"=>$user['type'],
                    "name"=>$user['name'],
                    "email"=>$user['email'],
                    "avatar"=>$user['avatar'],
                ]
            ];
            //保存session
            session($sessiondata);
        }
        //跳转
        return redirect(session("previous_url","/home"));
    }


    public function logout(){
        session()->forget('user');
        return redirect()->back();
    }

    public function testLogin()
    {
        //记录登录前的地址
        session(array("previous_url"=>URL::previous()));
        if (empty(session("user"))) {
            $sessiondata=[
                "user"=>[
                    "id"=>1,
                    "type"=>0,
                    "name"=>'wcx',
                    "email"=>'861081655@qq.com',
                    "avatar"=>'http://test/images/home/4.jpg',
                ]
            ];
            //保存session
            session($sessiondata);
            //跳转
            return redirect('/');
        }
    }
}
